<?php
/**
 * 核心文件
 * 处理
 *  参数
 *  请求
 *  业务转发
 *  输出
 * 
 * @package ews
 * @ews Enterprise WorkShop
 * @version 1.0 alpha
 * @since 2011-05-03
 * @author monkee
 */

class Core
{
	private $_g;
	
	function __construct(){
		$this->_g = array();
		$this->_request();
		$this->_init();
		
	}
	
	/**
	 * 执行
	 * 
	 */
	public function run(){
		$app = $this->getData('app');
		$method = $this->getData('method');
		empty($app) && $app = 'home';
		empty($method) && $method = 'index';
		$dir = ROOT.DIR_APP;
		if(is_file($dir.$app.'.app.php')){
			include_once $dir.$app.'.app.php';
			$app .= 'App';
			$appobj = new $app();
			if(method_exists($appobj, $method)){
				$data = $appobj->$method();
			}else{
				$this->msg("错误的访问请求！");
			}
		}else{
			$this->msg("错误的访问请求！");
		}
		$this->output($data);
	}
	
	/**
	 * 输出
	 * 
	 * @param mixed $data
	 */
	public function output($data){
		header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
		header('Cache-Control: no-store, no-cache, must-revalidate'); // HTTP/1.1 
		header('Cache-Control: pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
		header("Pragma: no-cache");
		header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
		header('Content-Type: text/html; charset=utf-8');
		Cookie::_set();
		if($ob_content = ob_get_length()){
			if(DEBUG){
				ob_end_flush();
				exit;
			}
			ob_clean();
		}
		$data = (array)$data;
		if(INAJAX == 2){
			header("Content-Type:text/html;charset=utf-8");
			echo json_encode($data);
			ob_end_flush();
			exit;
		}
		
		$app = $this->getData('app');
		$method = $this->getData('method');
		empty($app) && $app = 'home';
		empty($method) && $method = 'index';
		
		$tpl = ROOT.DIR_TPL.$app.'_'.$method.'.tpl.php';
		if(DEBUG || !is_file($tpl)){
			$this->make_template($tpl);
		}
		$user = $this->current_user();
		extract($data);
		include_once $tpl;
		exit;
	}
	
	/**
	 * 获取相关数据
	 * 
	 * @param string $str
	 */
	public function getData($str){
		$s = explode('/', $str);
		$r = & $this->_g;
		foreach($s as $i){
			if(isset($r[$i])){
				$r = & $r[$i];
			}else{
				return null;
			}
		}
		return $r;
	}
	
	/**
	 * 获取当前登陆用户
	 * 
	 */
	public function current_user(){
		$user = $this->getData('user');
		if(empty($user)){
			$uid = Cookie::get('user_id');
			$uid = intval($uid);
			if($uid > 0){
				$userobj = &$this->getModel('user');
				$this->_g['user'] = $userobj->get_user_by_user_id($uid);
				$user = $this->_g['user'];
			}
		}
		return $user;
	}
	
	/**
	 * 获取模型
	 * 
	 * @param unknown_type $str
	 */
	public function &getModel($str){
		if(!class_exists($app.'Mod')){
			$file = ROOT.DIR_MOD.$str.'.mod.php';
			if(!is_file($file)){
				$this->msg("MOD：{$str} 不存在！");
			}
		}
		$obj = $this->getData("mod/{$str}");
		if(!$obj){
			$css = $str.'Model';
			include_once $file;
			$this->_g['mod'][$str] = new $css();
			$obj = & $this->_g['mod'][$str];
		}
		return $obj;
	}
	
	/**
	 * 
	 */
	public function msg($msg, $type = 'info'){
		$this->_g['app'] = 'system';
		$this->_g['method'] = 'message';
		$this->output(array('msg' => $msg, 'type' => $type));
	}
	
	public function make_template($tpl){
		$app = $this->getData('app');
		$method = $this->getData('method');
		empty($app) && $app = 'index';
		empty($method) && $method = 'index';
		if(!class_exists('template')){
			include ROOT.'source/core/template.class.php';
		}
		$content = template::parse("{$app}/{$method}");
		if($content === -1){
			exit("Template file [{$app}/{$method}] not exist!");
		}
		file_put_contents($tpl, $content);
	}
	
	/**
	 * 初始化
	 * 
	 * ——导入配置
	 * ——处理请求
	 */
	private function _init(){
		ob_start();
		$this->_g['config'] = include_once(ROOT.'source/config.ini.php');
		$this->_g['inajax'] = empty($this->_g['get']['inajax']) ? (empty($this->_g['post']['inajax']) ? 0 : intval($this->_g['post']['inajax'])) : intval($this->_g['get']['inajax']);
		//调用接口返回格式
		//0：页面
		//1：htm输出，主要为窗口
		//2：json输出
		define('INAJAX', in_array($this->_g['inajax'], array(0, 1, 2)) ? intval($this->_g['inajax']) : 0);
		
		/** 设置时区 */
        date_default_timezone_set('Asia/Chongqing');
        
        /** TIMESTAMP 定义当前时间戳 */
        define('TIMESTAMP',time());
        define('CLIENTIP', get_client_ip());
        /** 当前登陆用户 */
        $this->_g['user'] = $this->current_user();
        $this->_g['app'] = trim($this->_g['get']['app']);
		$this->_g['method'] = trim($this->_g['get']['method']);
		
	}
	
	/**
	 * 请求处理
	 * 
	 */
	private function _request(){
		$this->_g['get'] = & $_GET;
		$this->_g['post'] = & $_POST;
		$this->_g['request'] = & $_REQUEST;
		$this->_g['server'] = & $_SERVER;
		$this->_g['file'] = & $_FILES;
		$this->_g['cookie'] = & $_COOKIE;
	}
}

/**
 * cookie的处理
 * @author monkee
 *
 */
class Cookie
{
	/**
	 * 配置COOKIE
	 * @param string $var	cookie名
	 * @param string $value	cookie值
	 * @param int $expire	生存周期
	 * 
	 * @return void
	 */
	static public function set($var = '', $value = '', $expire = 0){
		static $cookie = array();
		if(empty($var)){
			return $cookie;
		}
		
		$cookie[] = array('var' => $var, 'value' => $value, 'expire' => $expire);
	}
	/**
	 * 获取cookie的值
	 * @param string $var cookie名
	 * @return string value
	 */
	static public function get($var){
		return $_COOKIE[self::name($var)];
	}
	/**
	 * 设置cookie名称
	 * Enter description here ...
	 * @param string $var 变量名
	 * @return string $value
	 */
	static public function name($var){
		return COOKIE_PRE.$var;
	}
	static public function _set(){
		$cookie = Cookie::set();
		foreach($cookie as $item){
			$expire = intval($item['expire']);
			setcookie(self::name($item['var']), $item['value'], $expire > 0 ? time() + $expire : $expire, '/');
		}
	}
}
?>